package cn.yunhe.action;

import cn.yunhe.pojo.Book;
import cn.yunhe.service.BookService;
import cn.yunhe.util.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UpdateBookAction4 extends BaseAction implements ModelDriven {
    private Book book;

    private File upload;
    private String uploadContentType;
    private String uploadFileName;

    private String uploadSavePath;


    BookService bookService=new BookService();
    public String updateBook() throws IOException {
        System.out.println("<====book.getBname()======>"+book.getBname());
        System.out.println("<====book.getBpic()====1==>"+book.getBpic());

        String uploadFinalSavePath=getUploadSavePath()+"\\"+getUploadFileName();
        doupload(upload,uploadFinalSavePath);

        book.setBpic(getUploadFileName());
        System.out.println("<====book.getBpic()===2===>"+book.getBpic());
        boolean flag=bookService.updateBook(book);
        if (flag){
            return SUCCESS;
        }else {
            return null;
        }
    }

    private void doupload(File file,String finalSavePath) throws IOException {
        FileInputStream fis=new FileInputStream(file);
        byte[] buffer=new byte[1024];
        int length=-2;

        FileOutputStream fos=new FileOutputStream(finalSavePath);

        length=fis.read(buffer);
        while (length!=-1){
            fos.write(buffer);
            length=fis.read(buffer);
            System.out.println("<==length===>"+length);
        }

        fis.close();
        fos.close();

    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public String getUploadContentType() {
        return uploadContentType;
    }

    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getUploadSavePath() {
        /*return uploadSavePath;*/
        return ServletActionContext.getServletContext().getRealPath(uploadSavePath);
    }

    public void setUploadSavePath(String uploadSavePath) {
        this.uploadSavePath = uploadSavePath;
    }

    @Override
    public Book getModel() {
        if (book==null){
            book=new Book();
        }
        return book;
    }

}
